import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

public class main {

	public static void main(String[] args){

		// Variables Initialization
		int socketPort = 11111;
		boolean isRunning = false;
		ServerSocket serverSock = null;
		Socket cs = null;
		byte[] buffer = new byte[1024];
		String clientRequest = "";
		
		System.out.println("Initializing the Server...");

		try {
			serverSock = new ServerSocket(socketPort);
			isRunning = true;
			System.out.println("Server Initialized, Listening on port: "+ socketPort);
		}
		catch (IOException e) {
			System.err.println(e.getMessage());
			System.exit(1);
		}

		while (isRunning) {

			System.out.println("Waiting for connections...");

			try { cs = serverSock.accept(); }
			catch (IOException e) {
				e.printStackTrace();
				System.exit(2);
			}

			try {
				BufferedOutputStream b = new BufferedOutputStream(cs.getOutputStream());
				PrintStream os = new PrintStream(b,false);
				
				BufferedInputStream i = new BufferedInputStream(cs.getInputStream());
			
				int bytesRead = 0;
				clientRequest = "";
				while ((bytesRead = i.read(buffer)) != -1) {
	                
	                //Process the clientRequest of bytes read
	                //in this case we just construct a String and print it out
	                clientRequest = new String(buffer, 0, bytesRead);
	                break; 	
	            }
				
				System.out.println("clientRequest FROM CLIENT: "+clientRequest);
				
				boolean isAuth = checkLogin(clientRequest);
				
				os.print(isAuth);
				
				// Close the connection
				os.close(); 
				cs.close();
			}
			catch (Exception e) {
				System.out.println("Error: " +e);
				System.exit(3);
			}

		}

	}

	private static boolean checkLogin(String cr) throws SQLException, NoSuchAlgorithmException {
		
		String[] data = cr.split("\\|");
		
		DBConnection dbconn = new DBConnection();
		dbconn.connect();
		
		System.out.println("username: "+data[0]);
		System.out.println("password: "+data[1]);
		
		String query = "SELECT COUNT(*) FROM `user` WHERE username = '"+data[0]+"' AND password = '"+data[1]+"'";
		String count = dbconn.query(query);
		
		if(count.equalsIgnoreCase("1")) return true;
		else return false;

	}
}